import clog from './CLog';
import EventEmit, { IEvent } from './Event';
import Response, { Code } from './Response';

class Video {
	public container: HTMLVideoElement | null;
	public videoID: string;
	private isFloatWindowOpen: boolean = false;

	constructor(videoID: string) {
		this.videoID = videoID;
		this.container = (document.getElementById(videoID) as HTMLVideoElement) || null;
		this.addEventListener();
	}

	public validatePictureInPicture() {
		if ('pictureInPictureEnabled' in document) {
			return true;
		}
		return false;
	}
	private hasPictureInPicture() {
		if (document.pictureInPictureElement && document.pictureInPictureElement.id !== 'float-alert-video') {
			return true;
		}
		return false;
	}

	public entryPictureInPicture() {
		if (this.validatePictureInPicture() && this.container) {
			try {
				// 如果浮窗在picture in picture状态，先退出
				if (document.pictureInPictureElement?.id === 'float-alert-video') {
					this.isFloatWindowOpen = true;
					document.exitPictureInPicture();
				}
				this.container.requestPictureInPicture();
			} catch (error) {
				console.log('entry picture in picture error');
				this.setResponse(IEvent.PICTURE_IN_PICTURE, Response.PICTURE_IN_PICTURE_ERROR, { mode: 'entry', video: this.videoID });
			}
		}
	}

	public async exitPictureInPicture(pipMode = true) {
		if (pipMode && this.hasPictureInPicture()) {
			try {
				await document.exitPictureInPicture();
			} catch (error) {
				console.log('exit picture in picture error');
				this.setResponse(IEvent.PICTURE_IN_PICTURE, Response.PICTURE_IN_PICTURE_ERROR, { mode: 'exit', video: this.videoID });
			}
		}
	}

	public addEventListener() {
		if (this.container) {
			this.container.addEventListener('enterpictureinpicture', (event) => {
                if (event.target === this.container) {
                    this.setResponse(IEvent.PICTURE_IN_PICTURE, Response.PICTURE_IN_PICTURE_SUCCESS, { mode: 'entry', video: this.videoID });
                }
            });

			this.container.addEventListener('leavepictureinpicture', (event) => {
                if (event.target === this.container) {
                    this.setResponse(IEvent.PICTURE_IN_PICTURE, Response.PICTURE_IN_PICTURE_SUCCESS, { mode: 'exit', video: this.videoID });
                    // 如果之前关闭了浮窗，再打开
                    if (this.isFloatWindowOpen) {
                        this.isFloatWindowOpen = false;
                        this.setResponse(IEvent.REOPEN_FLOAT_WINDOW, 0, {});
                    }
                }
            });
		}
	}

	public removeEventListener() {
		this.container?.removeEventListener('enterpictureinpicture', () => {});
		this.container?.removeEventListener('leavepictureinpicture', () => {});
	}

	public previoustrack() {
		navigator.mediaSession.setActionHandler('previoustrack', () => {});
	}

	public nexttrack() {
		navigator.mediaSession.setActionHandler('nexttrack', () => {});
	}

	public close() {
		this.exitPictureInPicture();
		this.removeEventListener();
		this.videoID = '';
		this.container = null;
	}

	private setResponse(event: IEvent, code: Code, response: object | null) {
		let data = Response.creteResponseWithCode(code as number, response);
		// 统一错误处理
		EventEmit.setServiceEventListener(event, data);
		clog.error(code as number, response);
	}
}

export default Video;
